package models

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	_ "github.com/go-sql-driver/mysql"
	"strings"
	"time"
)

type IpccConfCallIn struct {
	Id           uint64 `orm:"pk;auto"`
	Number       string
	TransferType string
	Content      string
	Update       time.Time `orm:"description(修改时间);auto_now_add; type(datetime)"`
}

func RegisterConfCallIn() {
	orm.RegisterModel(new(IpccConfCallIn))
}

func GetTransferInfo(number string) (string, string, error) {

	result := &IpccConfCallIn{}

	o := orm.NewOrm()
	err := o.QueryTable(new(IpccConfCallIn)).Filter("Number", number).One(result)
	if err != nil {
		logs.Error("查询呼入配置信息 %v 失败:%v", number, err)
		return "", "", err
	}

	return result.TransferType, result.Content, err
}

func InsertNewCallInConf(number, transferType, content string) {

	newConf := &IpccConfCallIn{
		Number:       number,
		TransferType: transferType,
		Content:      content,
		Update:       time.Now(),
	}

	o := orm.NewOrm()
	err := o.QueryTable("IpccConfCallIn").Filter("Number", number).One(newConf)
	if err == nil {
		newConf.TransferType = transferType
		newConf.Content = content
		_, err = o.Update(newConf)
		if err != nil {
			logs.Error("number:%v 呼入设置保存失败:%v", number, err)
		}
	} else {
		if strings.Contains(err.Error(), "no row found") {
			_, err = o.Insert(newConf)
			if err != nil {
				logs.Error("number:%v 呼入设置保存失败:%v", number, err)
			}
		} else {
			logs.Error("number:%v 呼入设置保存失败:%v", number, err)
		}
	}
}
